﻿namespace MqttSample
{
    /// <summary>
    /// IMultiMqttClientWrapper
    /// </summary>
    public interface IMultiMqttClientWrapper : IDisposable
    {
        /// <summary>
        /// 启动MQTT客户端
        /// </summary>
        Task StartClientAsync();

        /// <summary>
        /// 数据输出
        /// </summary>
        event Action<MqttClientOption, CallbackData> MultiOutEventData;
    }


    /// <summary>
    /// MultiMqttClientWrapper
    /// </summary>
    public class MultiMqttClientWrapper : IMultiMqttClientWrapper, IMqttCallback
    {
        private List<MqttClientWrapper> _clientWrapperList;
        /// <summary>
        /// 数据输出
        /// </summary>
        public event Action<MqttClientOption, CallbackData> MultiOutEventData;

        /// <summary>
        /// ctor
        /// paramter is null throw exception
        /// </summary>
        public MultiMqttClientWrapper(params MqttClientOption[] option)
        {
            if (option == null) throw new ArgumentNullException("option");
            _clientWrapperList = new List<MqttClientWrapper>();
            foreach (var item in option)
            {
                _clientWrapperList.Add(new MqttClientWrapper(item, this));
            }
        }


        /// <summary>
        /// 启动mqtt客户端
        /// </summary>
        public async Task StartClientAsync()
        {
            foreach (var client in _clientWrapperList)
            {
                await client.StartAsync();
            }
        }

        /// <summary>
        /// mqtt 相关数据返回
        /// </summary>
        public Task OutEventDataAync(MqttClientOption option, CallbackData data)
        {
            MultiOutEventData?.Invoke(option, data);
            return Task.CompletedTask;
        }

        #region IDisposable
        public void Dispose()
        {
            _clientWrapperList.ForEach((client) =>
            {
                client.Dispose();
            });
        }
        #endregion
    }
}
